package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.models.*;
import com.aliyun.iot20180120.Client;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.stream.Collectors;

import static com.zzyl.common.constant.CacheConstants.IOT_PRODUCT_LIST_ALL;

/**
 * 设备管理Service业务层处理
 *
 * @author guo
 * @date 2024-11-19
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Resource
    private Client client;

    @Resource
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     *
     * @return
     */
    @Override
    public void syncProductList() {
        //查询阿里iot平台上的所有产品
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        queryProductListRequest.setPageSize(10);
        queryProductListRequest.setCurrentPage(1);
        // 设置实例id
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductListResponse queryProductListResponse = null;
        try {
            //查询
            queryProductListResponse = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            log.error("查询阿里所有iot产品失败!", e);
            throw new ServiceException("查询阿里所有iot产品失败!");
        }
        //解析结果
        if (!queryProductListResponse.getBody().success) {
            throw new ServiceException("查询阿里所有iot产品失败!");
        }
        //转成VO存入redis
        List<ProductVo> productVoList = queryProductListResponse.getBody().getData().getList().getProductInfo().stream()
                .map(pro -> BeanUtil.toBeanIgnoreError(pro, ProductVo.class)).collect(Collectors.toList());
        //集合转成json字符串
        String jsonString = JSONUtil.toJsonStr(productVoList);
        //存入redis
        redisTemplate.opsForValue().set(IOT_PRODUCT_LIST_ALL, jsonString);
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonString = redisTemplate.opsForValue().get(IOT_PRODUCT_LIST_ALL);
        return JSONUtil.toList(jsonString, ProductVo.class);
    }
    /**
     * 查询设备详细数据
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //1. 查询aliyun平台数据iot设备详细数据
        DeviceVo deviceVo = queryDeviceInAliyun(deviceDto);

        //2. 查询数据库中的device表数据
        Device device = lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()).one();

        //3. 合并数据并返回 CopyOptions: 复制属性，忽略null值
        BeanUtil.copyProperties(device,deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    /**
     * 查看指定产品的物模型中的功能定义详情
     * @param request
     * @return
     */
    @Override
    public Object queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            QueryThingModelPublishedResponse response = client.queryThingModelPublished(request);
            if (response.getBody().success) {
                return response.getBody().getData();
            }
        } catch (Exception e) {
            log.error("查看指定产品的物模型中的功能定义详情失败!",request.getProductKey(),e);
        }
        throw new ServiceException("查看指定产品的物模型中的功能定义详情失败!");
    }

    /**
     * 查询指定设备的物模型运行状态
     * @param request
     * @return
     */
    @Override
    public Object queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            QueryDevicePropertyStatusResponse response = client.queryDevicePropertyStatus(request);
            if (response.getBody().success) {
                return response.getBody().getData();
            }
        } catch (Exception e) {
            log.error("获取设备物模型的运行状态失败!",e);
        }
        throw new ServiceException("获取设备物模型的运行状态失败!");
    }

    /**
     * 查询aliyun平台数据iot设备详细数据
     * @param deviceDto
     * @return
     */
    private DeviceVo queryDeviceInAliyun(DeviceDto deviceDto) {
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(deviceDto.iotId);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            QueryDeviceDetailResponse response = client.queryDeviceDetail(request);
            if (response.getBody().success) {
            return BeanUtil.toBeanIgnoreError(response.getBody().getData(), DeviceVo.class);
        }
        } catch (Exception e) {
            log.error("查询设备详细信息失败",e);
        }
        throw new ServiceException("查询Iot设备详细信息失败");
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1. 判断设备名称是否重名
        Device deviceInDb = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).one();
        if (ObjectUtil.isNotEmpty(deviceInDb)) {
            //不为空就报错
            throw new ServiceException("设备名称已经存在" + deviceDto.getDeviceName());
        }
        //2. IOT新增设备
        addIotDevice(deviceDto);
        //3. 查询产品的名称 productName
        String productName = getProductName(deviceDto.getProductKey());
        //4. 构建设备对象
        Device device = BeanUtil.toBeanIgnoreError(deviceDto, Device.class);
        //设置productName
        device.setProductName(productName);
        //设置physical_location_type,因为前端没有传,
        //传了location_type,若为0代表随身设备
        //physical_location_type 0楼层 1房间 2床位
        if (ObjectUtil.equal(deviceDto.getLocationType(), 0)) {
            device.setPhysicalLocationType(-1);
        }
        //5. 添加到数据库设备表
        try {
            save(device);
        } catch (Exception e) {
            //删除设备
            deleteDevice(deviceDto.getIotId());
        }
    }


    /**
     * 删除设备
     *
     * @param iotId
     */
    private void deleteDevice(String iotId) {
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setIotId(iotId);
        try {
            DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            log.error("新增设备失败，删除iot设备【{}】失败.", iotId, e);
            throw new ServiceException("新增设备失败，删除iot设备失败");
        }

    }

    /**
     * 查询产品的名称 productName
     *
     * @param productKey
     * @return
     */
    private String getProductName(String productKey) {
        //获取缓存iot产品的列表
        String jsonStr = redisTemplate.opsForValue().get(IOT_PRODUCT_LIST_ALL);
        //转成list集合
        List<ProductVo> productVoList = JSONUtil.toList(jsonStr, ProductVo.class);
        //遍历根据key拿出value

        /*return productVoList.stream().filter(productVo -> productKey.equals(productVo.getProductKey()))
            .findFirst()
            .orElseThrow(() -> new ServiceException("没有对应的产品信息!"))
            .getProductName();*/

        for (ProductVo productVo : productVoList) {
            if (ObjectUtil.equal(productKey, productVo.getProductKey())) {
                return productVo.getProductName();
            }
        }
        throw new ServiceException("没有对应的产品信息");
    }

    /**
     * IOT新增设备
     *
     * @param deviceDto
     */
    private void addIotDevice(DeviceDto deviceDto) {
        try {
            RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
            registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            RegisterDeviceResponse response = client.registerDevice(registerDeviceRequest);

            if (response.getBody().success) {
                deviceDto.setIotId(response.getBody().getData().getIotId());
                return;
            }
        } catch (Exception e) {
            log.error("注册设备失败", e);
        }
        throw new ServiceException("注册设备失败");
    }
}
